package Servlets.xzh;

import Bean.admin.Admin;
import Util.GokJDBCUtil2;
import Util.RES;

import Util.SlatMD5Util;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@WebServlet(name = "AdminServlet", urlPatterns = "/AdminServlet")
public class AdminServlet extends HttpServlet {
    public void init() {
    }

    @Override
    public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException {

        int pageSize = 10;
        int totalPage = 0;
        int currentPage = req.getParameter("currentPage") == null ? 1 : Integer.parseInt(req.getParameter("currentPage"));
        if("新增管理员".equals(req.getParameter("textContext"))){

            res.setContentType("text/html;charset=utf-8");
            String adminaccount = req.getParameter("adminaccount");
            String adminpassword = req.getParameter("adminpassword");
            String password = SlatMD5Util.generateSaltPassword(adminpassword);
            String adminname = req.getParameter("adminname");
            String adminstatus = req.getParameter("adminstatus");
            String sql = "insert into admin (adminaccount,adminpassword,adminname,adminstatus,createtime,updatetime) values (?,?,?,?,now(),now())";
            int insert = GokJDBCUtil2.update(sql, adminaccount, password, adminname, adminstatus);
            if(insert == 1){
                PrintWriter writer = res.getWriter();
                writer.print(RES.success("新增成功"));
                writer.close();
            }else{
                PrintWriter writer = res.getWriter();
                writer.print(RES.fail("新增失败"));
                writer.close();
            }

        } else if ("删除".equals(req.getParameter("textContext"))) {
            log.info("删除");
            int id = Integer.parseInt(req.getParameter("id"));
            String sql = "update admin set isdeleted = 1 where id = ?";
            int update = GokJDBCUtil2.update(sql, id);
            if(update == 1){
                PrintWriter writer = res.getWriter();
                writer.print(RES.success("删除成功"));
                writer.close();

            }else{
                PrintWriter writer = res.getWriter();
                writer.print(RES.fail("删除失败"));
                writer.close();
            }
        } else if("编辑管理员".equals(req.getParameter("textContext"))){
            res.setContentType("text/html;charset=utf-8");
            int id = Integer.parseInt(req.getParameter("id"));
            String adminaccount = req.getParameter("adminaccount");
            String adminpassword = req.getParameter("adminpassword");
            String password = SlatMD5Util.generateSaltPassword(adminpassword);
            String adminname = req.getParameter("adminname");
            String adminstatus = req.getParameter("adminstatus");
            String sql = "update admin set adminaccount=? , adminpassword = ? , adminname = ? , adminstatus = ? , updatetime = now() where id = ?";
            int update = GokJDBCUtil2.update(sql, adminaccount, password, adminname, adminstatus, id);
            if(update == 1){
                PrintWriter writer = res.getWriter();
                writer.print(RES.success("编辑成功"));
                writer.close();
            }else{
                PrintWriter writer = res.getWriter();
                writer.print(RES.fail("编辑失败"));
                writer.close();
            }

        } else if ("checkAdminaccount".equals(req.getParameter("textContext"))) {
            String adminaccount = req.getParameter("adminaccount");
            String Id = req.getParameter("id");
            StringBuilder sql = new StringBuilder("select * from admin where adminaccount = ? ");
            if(Id!=null && !Id.isEmpty()){
                int id = Integer.parseInt(Id);
                sql.append("and id != ").append(id);
            }
            int i = GokJDBCUtil2.queryForCount(sql.toString(), adminaccount);
            if(i>0){
                PrintWriter writer = res.getWriter();
                writer.print(RES.fail("用户名重复"));
                writer.close();
            }else{
                PrintWriter writer = res.getWriter();
                writer.print(RES.success("用户名可用"));
                writer.close();
            }
        } else{
            String adminaccount = req.getParameter("adminaccount");
            String adminname = req.getParameter("adminname");

            StringBuilder sql = new StringBuilder();
            sql.append("select * from admin where isdeleted = 0");

            //查询总页数
            List<Admin> admins_all = GokJDBCUtil2.queryAll(sql.toString(),Admin.class);
            totalPage = (int) Math.ceil((double) admins_all.size()/pageSize);

            //查询条件
            List<Object> params = new ArrayList<Object>();
            if(adminaccount != null && !adminaccount.trim().isEmpty()){
                sql.append(" and adminaccount like " + "'%" + adminaccount + "%'");
                params.add(adminaccount);
            }
            if(adminname != null && !adminname.trim().isEmpty()){
                sql.append(" and adminname like " + "'%" + adminname + "%'");
                params.add(adminname);
            }
            sql.append(" limit ?,?");
            List<Admin> admins_select = GokJDBCUtil2.queryAll(sql.toString(),Admin.class,(currentPage-1)*pageSize,pageSize);
            req.setAttribute("admins", admins_select);
            req.setAttribute("currentPage", currentPage);
            req.setAttribute("pageSize", pageSize);
            req.setAttribute("totalPage", totalPage);
            req.setAttribute("adminaccount", adminaccount);
            req.setAttribute("adminname", adminname);

            req.getRequestDispatcher("/pages/admin_manage/admin_manage.jsp").forward(req,res);


        }
    }
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
        String method = req.getMethod();
        try {
            if (method.equals("GET")) {
                this.doGet(req, res);
            } else if (method.equals("POST")) {
                this.doGet(req, res);
            } else {
                PrintWriter writer = res.getWriter();
                writer.println("{\"code\":\"400\",\"msg\":\"此方法不允许\"}");
                writer.close();
            }
        } catch (Exception e) {
            log.error("服务器处理请求时发生错误", e);
            PrintWriter writer = res.getWriter();
            writer.println("{\"code\":\"500\",\"msg\":\"服务器处理请求时发生错误\"}");
            writer.close();
        }
    }
    public void destroy() {
    }
}